import tushare as ts
import pandas as pd
from pythondemo.Pandas_Tushare.config_mysql import ConfSQL
import time


def transfer_stock_date(code, start, end):
    df = ts.pro_bar(ts_code=code, adj='qfq', start_date=start,
                    end_date=end)
    return df


class GetStock(object):

    def __init__(self):
        ts.set_token("30d023679cd931ae49506267e9a80fdba42641655150c8fa656ae416")
        self.data = []
        self.pro = ts.pro_api()
        self.conf_sql = ConfSQL()

    # 获取当前所有正常上市交易的股票代码
    def get_stock_code(self):

        self.data = self.pro.stock_basic(exchange='', list_status='L',
                                         fields='ts_code,symbol,name,area,industry,list_date')
        # 剔除名字中包含ST的股票
        self.data = self.data[~self.data.name.str.contains('ST')]
        self.conf_sql.put_sql(self.data, 'stockCodes', 'replace')
        print('stockCodes插入SQL完成')

    # 获取每一只股票的历史数据
    def code_frame(self):
        codes = getattr(self.conf_sql.get_sql('stockCodes'), 'ts_code')
        # 记录请求次数
        count = 0
        start_time = time.time()
        for row in codes:
            trans = row.replace('.', '_')
            df = ts.pro_bar(ts_code=row, adj='qfq', start_date='20200101',
                            end_date=time.strftime('%Y%m%d'))
            df['trade_date'] = pd.to_datetime(df["trade_date"])
            df.set_index('trade_date', inplace=True)
            self.conf_sql.to_sql(df, trans, 'replace')
            print(trans, '写入SQL完成')
            count = count + 1
            end_time = time.time()
            # 记录消耗时间
            expend = end_time - start_time
            if count >= 499 and expend <= 59:
                print('已过量，等待:{}秒，重新开始'.format(61 - expend))
                time.sleep(61 - expend)
                count = 0
                start_time = time.time()

    def update_stock(self):
        _codes = getattr(self.conf_sql.get_sql('stockCodes'), 'ts_code')
        # 记录请求次数
        _count = 0
        _start_time = time.time()
        for row in _codes:
            _trans = row.replace('.', '_')
            _trade = getattr(self.conf_sql.read_sql(_trans, 1), 'trade_date')
            _update_sql = ts.pro_bar(ts_code=row, adj='qfq', start_date=str(int(_trade[0]) + 1),
                                     end_date=time.strftime('%Y%m%d'))
            _update_sql['trade_date'] = pd.to_datetime(_update_sql["trade_date"])
            _update_sql.set_index('trade_date', inplace=True)
            self.conf_sql.put_sql(_update_sql, _trans, 'append')
            print(_trans, '更新SQL完成')
            _count += 1
            _end_time = time.time()
            # 记录消耗时间
            _expend = _end_time - _start_time
            if _count >= 499 and _expend <= 59:
                print('已过量，等待:{}秒，重新开始'.format(61 - _expend))
                time.sleep(61 - _expend)
                _count = 0
                _start_time = time.time()

    def cal_date(self):
        # 获取最近交易日
        cd = self.pro.trade_cal(exchange='SSE', start_date=int(time.strftime('%Y%m%d')) - 10,
                                end_date=time.strftime('%Y%m%d'), is_open=1)
        cd['cal_date'] = pd.to_datetime(cd["cal_date"])
        end_date = getattr(cd[-1:], 'cal_date')
        return int(end_date)

    def bak_date(self):
        a = self.pro.bak_daily(ts_code='600519.SH', start_date='20200101', end_date='20210101')
        print(a.loc[:, ["float_mv"]])


def from_code(code):
    prices = ts.get_realtime_quotes(code)
    return prices


class GetTodayStock(object):
    """
    from_code:
                传入code:
                            请求多个股票方法（一次最好不要超过30个）：
                            #symbols from a list
                            ts.get_realtime_quotes(['600848','000980','000981'])
                            #from a Series
                            ts.get_realtime_quotes(df['code'].tail(10))  #一次获取10个股票的实时分笔数据

                            获取实时指数：

                            #上证指数
                            ts.get_realtime_quotes('sh')
                            #上证指数 深圳成指 沪深300指数 上证50 中小板 创业板
                            ts.get_realtime_quotes(['sh','sz','hs300','sz50','zxb','cyb'])
                            #或者混搭
                            ts.get_realtime_quotes(['sh','600848'])
                返回dataframe类型：
                            0：name，股票名字
                            1：open，今日开盘价
                            2：pre_close，昨日收盘价
                            3：price，当前价格
                            4：high，今日最高价
                            5：low，今日最低价
                            6：bid，竞买价，即“买一”报价
                            7：ask，竞卖价，即“卖一”报价
                            8：volume，成交量 maybe you need do volume/100
                            9：amount，成交金额（元 CNY）
                            10：b1_v，委买一（笔数 bid volume）
                            11：b1_p，委买一（价格 bid price）
                            12：b2_v，“买二”
                            13：b2_p，“买二”
                            14：b3_v，“买三”
                            15：b3_p，“买三”
                            16：b4_v，“买四”
                            17：b4_p，“买四”
                            18：b5_v，“买五”
                            19：b5_p，“买五”
                            20：a1_v，委卖一（笔数 ask volume）
                            21：a1_p，委卖一（价格 ask price）
                            ...
                            30：date，日期；
                            31：time，时间；
    """

    # def __init__(self):
    #     self.conf_sql = ConfSQL()


# class MoreThread(threading.Thread):
#
#     def __init__(self, func, args='', name=None):
#         threading.Thread.__init__(self)
#         self.func = func
#         self.args = args
#         self.name = name
#
#     def run(self):
#         self.func(*self.args)

#
if __name__ == '__main__':
    GetStock().get_stock_code()